package com.airbat.prize.utils;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName JsonUtil
 * @Description JSON工具
 * @Author wmj
 * @Date 2022/8/8 20:39
 * @Project ds
 * @Version 1.0
 */
public class JsonUtil {
    /**
     * json字符串替换下划线key为驼峰名
     * @param sourceJson
     * @return
     */
    public static String relaceKey(String sourceJson){
        JSONObject rootObject=  JSONObject.parseObject(sourceJson);
        JSONObject resultJson=relaceKey(rootObject);
        return  resultJson.toJSONString();
    }

    /**
     * 替换Json的key，下划线改驼峰名
     * @param jsonObject
     * @return
     */
    public static JSONObject relaceKey(JSONObject jsonObject){
        JSONObject newObject= new JSONObject();
        for(String oldKey: jsonObject.keySet()){
            if(oldKey.length()>1) {//单字符属性反射会报错，直接扔掉
                Object value = jsonObject.get(oldKey);
                if (value instanceof List) {
                    List<JSONObject> childList = (List<JSONObject>) value;
                    List<JSONObject> newChildren = new ArrayList<>();
                    for (JSONObject child : childList) {
                        child = relaceKey(child);
                        newChildren.add(child);
                    }
                    value = newChildren;
                }
                if (value instanceof JSONObject) {
                    JSONObject child = (JSONObject) value;
                    value = relaceKey(child);
                }
                String newKey = StringCaseUtil.lineToCamel(oldKey, "_");
                newObject.put(newKey, value);
//            jsonObject.remove(oldKey);
            }
        }
        return newObject;
    }

}
